#include <stdio.h>

#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>

#include "../include/const.h"
#include "../include/tools.h"

#include "../include/log.h"

using namespace std;

Log ts_log; // 全局日志文件

string Log::genHead(const string &who)
{
    string ret;
    ret = getDateNow() + " ";
    ret += getTimeNow();
    ret += " [";
    ret += who;
    ret += "] ";
    return ret;
}
string Log::genHead(uint who)
{
    string ret;
    ret = getDateNow() + " ";
    ret += getTimeNow();
    ret += " [";
    ret += to_string(who);
    ret += "] ";
    return ret;
}

string Log::binaryToLog(const char *binary, int data_len)
{
    ostringstream oss;
    oss << hex << setfill('0');
    for (int i = 0; i <= (data_len - 1) / 16; i++)
    {
        oss << "  " << setw(4) << i * 16 << ":  ";
        string content;
        for (int chi = i * 16; chi < min((i + 1) * 16, data_len); chi++)
        {
            if (chi % 8 == 0 && chi % 16 != 0 && chi != data_len - 1)
                oss << "- ";
            oss << setw(2) << (int)(uchar)binary[chi] << " ";
            content += binary[chi] >= ' ' && binary[chi] <= 0x7e ? binary[chi] : '.';
        }
        oss << "\t" << content << endl;
    }
    return oss.str();
}

Log::~Log()
{
    if (log_fd.is_open())
        log_fd.close();
}

int Log::openFile(const char *file_path, bool do_del_log)
{
    auto mode = do_del_log ? ios::out : ios::out | ios::app;
    log_fd.open(file_path, mode);
    return log_fd.is_open() ? 0 : -1;
}

int Log::writePrompt(const string &who, const string &prompt)
{
    log_fd << genHead(who) << prompt << endl;
    return 0;
}
int Log::writePrompt(uint who, const string &prompt)
{
    log_fd << genHead(who) << prompt << endl;
    return 0;
}

int Log::writeRaw(const string &content)
{
    log_fd << content << endl;
    return 0;
}
int Log::writeRaw(const char *content)
{
    log_fd << content << endl;
    return 0;
}